<?php

class statisticsController extends manageController {

    public function __construct() {
        if (!isset($_SESSION['zp_manage']['islogin']) || empty($_SESSION['zp_manage']['islogin'])) {
            Tools::AlertTxt('?md=manage&cl=login&at=login', '请先登录');
            exit;
        }
    }


    /**
     * 分司排行列表
     */
    public function companyRankingListAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);

        $days = $this->_getCountDays(strtotime($STime),strtotime($ETime));
        if($days>30){
            Tools::AlertTxt('?md=manage&cl=statistics&at=companyRankingList', '查询时间默认不超过 30 天');
            exit;
        }
        //抓列表
//        $where_fields = 'exp.status < 7'; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }
//        sum(a.actual_pay) as TotalPrice,
        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,t.company_id,x.name,x.code FROM 
          orders_express as exp  left join xd_store as t  ON exp.shop_no = t.store_id left join xd_company as x ON x.code = t.company_id where $where_fields group by t.company_id order by ExpressFee desc ";

//        echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_lists[] = $row;
            }

        }
        $this->view->setVariable("rsp_list", $rsp_lists);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/statistics/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }



    /**
     * 门店排行列表
     */
    public function storeRankingListAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);

        $days = $this->_getCountDays(strtotime($STime),strtotime($ETime));
        if($days>90){
            Tools::AlertTxt('?md=manage&cl=statistics&at=storeRankingList', '查询时间默认 90 天内');
            exit;
        }
        //抓列表
//        $where_fields = 'exp.status < 7 AND exp.express_fee is not null'; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }

//        sum(a.actual_pay) as TotalPrice,
        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,t.storename,t.store_id FROM
          orders_express as exp  left join xd_store as t  ON exp.shop_no = t.store_id where $where_fields group by exp.shop_no  order by ExpressFee desc ";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res_s = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res_s)) {
            while ($row_s = mysqli_fetch_array($res_s, MYSQLI_ASSOC)) {
                $store_list[] = $row_s;
            }
        }
//        echo '<pre>';
//        var_dump($store_list);die;
        $this->view->setVariable("rsp_list", $store_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/statistics/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 骑手列表
     */
    public function ridersRankingListAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);

        $days = $this->_getCountDays(strtotime($STime),strtotime($ETime));
        if($days>90){
            Tools::AlertTxt('?md=manage&cl=statistics&at=storeRankingList', '查询时间默认 90 天内');
            exit;
        }
        //抓列表
//        $where_fields = "exp.status < 7 AND exp.express_type = 'self' AND exp.express_mobile !=''"; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0 AND exp.express_type = "self"';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }

//        sum(a.actual_pay) as TotalPrice,
        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,r.name,r.tel FROM
          orders_express as exp  left join riders as r ON r.tel = exp.express_mobile  where $where_fields group by exp.express_mobile  order by ExpressFee desc";
//        echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res_s = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res_s)) {
            while ($row_s = mysqli_fetch_array($res_s, MYSQLI_ASSOC)) {
                $store_list[] = $row_s;
            }
        }
//        echo '<pre>';
//        var_dump($store_list);die;
        $this->view->setVariable("rsp_list", $store_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/statistics/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    function _getCountDays($sTime, $eTime)
    {
        $startDt = getdate($sTime);
        $endDt = getdate($eTime);
        $sUTime = mktime(12, 0, 0, $startDt['mon'], $startDt['mday'], $startDt['year']);
        $eUTime = mktime(12, 0, 0, $endDt['mon'], $endDt['mday'], $endDt['year']);
        return round(abs($sUTime - $eUTime) / 86400);
    }


    /**
     * 导出 分司排行
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function exportAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);
        //抓列表
//        $where_fields = 'exp.status < 7'; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }
        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,t.company_id,x.name,x.code FROM 
          orders_express as exp  left join xd_store as t  ON exp.shop_no = t.store_id left join xd_company as x ON x.code = t.company_id where $where_fields group by exp.shop_no";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if($rsp_list && is_array($rsp_list) && count($rsp_list) > 0){
            $titles = array('序号', '分司名称', '分司代码', '订单总量', '配送费总额');
            $tableName = "分司排行";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($rsp_list as $key => $row) {
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['name'] = $row['name'];
                $exportIinfo['code'] = $row['code'];
                $exportIinfo['OrderNumber'] = $row['OrderNumber'];
                $exportIinfo['ExpressFee'] = $row['ExpressFee'];
                echo implode("\t ,", $exportIinfo) . "\n";

            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:application/vnd.ms-excel');
            ob_end_flush();
            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'orders';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $this->model->setLog($log, $org, $exportIinfo);
            exit;
        }else{
            Tools::AlertTxt('?md=manage&cl=statistics&at=companyRankingList', '没有可汇出数据');
            exit;
        }

    }

    /**
     * 导出 门店排行
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function exportStoreAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);

        //抓列表
       // $where_fields = 'exp.status < 7'; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }

        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,t.storename,t.store_id FROM
          orders_express as exp  left join xd_store as t  ON exp.shop_no = t.store_id where $where_fields group by exp.shop_no";
        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }

        if($rsp_list && is_array($rsp_list) && count($rsp_list) > 0){
            $titles = array('序号', '門店名称', '門店代码', '订单总量', '配送费总额');
            $tableName = "门店排行_".date('YmdHis');
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t,", $titles), "\n";
            foreach ($rsp_list as $key => $row) {
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['storename'] = $row['storename'];
                $exportIinfo['store_id'] = $row['store_id'];
                $exportIinfo['OrderNumber'] = $row['OrderNumber'];
                $exportIinfo['ExpressFee'] = $row['ExpressFee'];
                echo implode("\t,", $exportIinfo), "\n";
            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');

            ob_end_flush();
            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'orders';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $this->model->setLog($log, $org, $exportIinfo);
            exit;
        }else{
            Tools::AlertTxt('?md=manage&cl=statistics&at=storeRankingList', '没有可汇出数据');
        }

    }


    /**
     * 导出 骑手配送排行
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function exportRiderAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $STime = (!empty($this->params['stime'])) ?  $this->params['stime'] : '';         # 订单完成时间
        $ETime = (!empty($this->params['etime'])) ?  $this->params['etime'] : '';         # 订单完成时间
        $this->view->setVariable("STime", $STime);
        $this->view->setVariable("ETime", $ETime);

        //抓列表
//        $where_fields = "exp.status < 7 AND exp.express_type = 'self'"; # 测试
        $where_fields = 'exp.status = 5 AND exp.isdeleted = 0';
        if (!empty($STime)) {
            $S_corder = $STime." 00:00:00";
            $where_fields .= " AND exp.updatedt > '$S_corder'";
        }
        if (!empty($ETime)) {
            $E_corder = $ETime." 00:00:00";
            $where_fields .= " AND exp.updatedt < '$E_corder' ";
        }

//        sum(a.actual_pay) as TotalPrice,
        $sql = "SELECT count(exp.id) as OrderNumber,sum(exp.express_fee) as ExpressFee,r.name,r.tel FROM
          orders_express as exp  left join riders as r ON r.tel = exp.express_mobile  where $where_fields group by exp.shop_no";
        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if($rsp_list && is_array($rsp_list) && count($rsp_list) > 0) {
            $titles = array('序号', '骑手姓名', '骑手电话', '订单总量', '配送费总额');
            $tableName = "骑手配送排行";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($rsp_list as $key => $row) {
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['storename'] = $row['name'];
                $exportIinfo['store_id'] = $row['tel'];
                $exportIinfo['OrderNumber'] = $row['OrderNumber'];
                $exportIinfo['ExpressFee'] = $row['ExpressFee'];
                echo implode("\t ,", $exportIinfo) . "\n";
            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:application/vnd.ms-excel');
            ob_end_flush();
            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'orders';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $this->model->setLog($log, $org, $exportIinfo);
            exit;
        }else{
            Tools::AlertTxt('?md=manage&cl=statistics&at=ridersRankingList', '没有可汇出数据');
        }
    }

}